package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final UserRoleMapper userRoleMapper;

    @Override
    public PageResponse<UserVo> findPage(UserDto userDto, Integer pageNum, Integer pageSize) {
        //先进性判断，如果前端有模糊查询部门id
        //前端先传入一个部门的编号到userDto对象中,对这个部门编号进性去零重新封装
        if (!(EmptyUtil.isNullOrEmpty(userDto.getDeptNo()))){
            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        }
        //分页工具进行分页
        PageHelper.startPage(pageNum,pageSize);

        //获取上述部门下的所有子节点数据
        List<User> list = userMapper.findPage(userDto);
        Page<User> page = (Page<User>) list;
        PageResponse<UserVo> pageResponse = PageResponse.of(page, UserVo.class);

        //如果响应结果不为空
        if (!(EmptyUtil.isNullOrEmpty(pageResponse.getRecords()))){
            //将records中的userVo集合对象拿出来，获取它们的userId
            // List<Long> userIds = pageResponse.getRecords().stream().map(userVo -> userVo.getId()).collect(Collectors.toList());
            List<Long> userIds = pageResponse.getRecords().stream().map(UserVo::getId).collect(Collectors.toList());
            List<RoleVo> roles = userRoleMapper.selectRolesByUserIds(userIds);
            // List<RoleVo> roles = new ArrayList<>();
            // for (Long userId : userIds) {
            //     RoleVo roleVo = userRoleMapper.selectRoleByUserId(userId);
            //     if (roleVo != null){
            //         roles.add(roleVo);
            //     }
            // }
            //将roleVoIds集合和roleLabels集合装配到每一个UserVo对象中
            //最主要的关系是一个用户对应了多个角色，所以要设置集合
            pageResponse.getRecords().forEach(n -> {
                Set<String> roleVoIds = new HashSet<>();
                Set<String> roleLabels = new HashSet<>();
                //对roles集合进行遍历
                roles.forEach(r -> {
                    //如果用户的id和用户角色中间的中间表的userId相同，就会把符合条件的role添加
                    if(String.valueOf(n.getId()).equals(String.valueOf(r.getUserId()))){
                        //向集合中添加对应role的id
                        roleVoIds.add(String.valueOf(r.getId()));
                        //向集合中添加对应role的roleName
                        roleLabels.add(String.valueOf(r.getRoleName()));
                    }
                });
                n.setRoleVoIds(roleVoIds);
                n.setRoleLabels(roleLabels);
            });
        }
        return pageResponse;
    }

    /**
     * 添加用户，因为还要添加用户对应角色的中间表，所以要调用两个mappeer方法
     * 使用Transactional注解，保证事务的原子性
     * @param userDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertUser(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        user.setDataState("0");
        Integer count1 = userMapper.insertUser(user);
        Set<String> roleVoIds = userDto.getRoleVoIds();
        UserRole userRole = null;
        Integer count2 = null;
        for (String roleVoId : roleVoIds) {
            userRole = UserRole.builder().dataState("0").roleId(Long.valueOf(roleVoId)).userId(user.getId()).build();
            count2 = userRoleMapper.insertUserRoles(userRole);
        }
        return count1 > 0 && count2 > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByUserId(String userIds) {
        userMapper.deleteByPrimaryKey(Long.valueOf(userIds));
        userRoleMapper.deleteMiddleByUserId(Long.valueOf(userIds));
    }

    @Override
    public void updateStatus(Long id, String status) {
        userMapper.updateStatus(id,status);
        // User user = User.builder().dataState(status).build();
        // user.setId(id);
        // userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public Boolean resetPassword(String userId) {
        Integer flag = userMapper.resetPassword(Long.valueOf(userId));
        return flag > 0;
    }

    @Override
    public Boolean updateUser(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        Integer count1 = userMapper.updateByPrimaryKeySelective(user);
        Set<String> roleVoIds = userDto.getRoleVoIds();
        Long userId = user.getId();
        userRoleMapper.deleteMiddleByUserId(userId);
        UserRole userRole = null;
        Integer count2 = null;
        for (String roleVoId : roleVoIds) {
            userRole = UserRole.builder().dataState("0").roleId(Long.valueOf(roleVoId)).userId(user.getId()).build();
            count2 = userRoleMapper.insertUserRoles(userRole);
        }
        return count1 > 0 && count2 > 0;
    }

    @Override
    public List<UserVo> findList() {
        List<UserVo> list = userMapper.findList();
        return list;
    }
}
